package com.jeady.timetodo.utils

import android.os.CountDownTimer
import android.util.Log
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import com.jeady.jxcompose.Utils

private val TAG = "[Utils]"
@Composable
fun CurrentDateTime(modifier: Modifier=Modifier, format:String="yyyy-MM-dd HH:mm:ss", onUpdate: ((timestamp: Long)->Unit)? = null){
    var currentTime by remember{ mutableStateOf("") }
    DisposableEffect(true) {
        var countDownTimer: CountDownTimer? = object: CountDownTimer(1000, 1000){
            override fun onTick(millisUntilFinished: Long) {
                currentTime = timeAfterMS(0, format)
                onUpdate?.invoke(currentTimestamp())
            }
            override fun onFinish() {
                start()
            }
        }
        countDownTimer?.start()
        onDispose {
            Log.d(TAG, "CurrentDateTime: dispose")
            countDownTimer?.cancel()
            countDownTimer=null
        }
    }
    Text(currentTime, modifier, fontWeight = FontWeight.ExtraBold, fontFamily = FontFamily.Serif)
}

fun currentTime(): String{
    return Utils.currentTimeString()
}

fun timeAfterMS(ms: Long, format: String="MM-dd HH:mm:ss"): String{
    // 经过ms之后的时间
    return Utils.formatDateTime(System.currentTimeMillis()+ms, format)
}

fun Long.timeFormat(format: String="yyyy-MM-dd HH:mm:ss"):String{
    return Utils.formatDateTime(this, format)
}

fun currentTimestamp(): Long{
    return System.currentTimeMillis()
}

fun timestampAfter(ms: Long): Long{
    return System.currentTimeMillis() + ms
}